/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}


/**
 * 去除空格
 * @param {String} v
 */
export function spaceClear(v) {
  return v ? v.replace(/\s+/g, '') : ''
}

export function getDateRand() {
  return new Date().getTime().toString() + Math.ceil(Math.random() * 100).toString()
}

/**
 * 格式化输入为整数或者小数,示例：onkeyup=decimalFormat(this,2,refname)
 * @param that 页面对象，必传
 * @param decimalfixed 要保留的小数位数，整数可不传，默认0
 * @param refname input控件ref名称，必传
 * create 2019-5-31 by yufei
 * */
export function decimalFormat(that, refname, decimalfixed) {
  var elem

  if (that.$refs[refname].length > 0) {
    elem = that.$refs[refname][0].$el.querySelector('input')// 获取页面input元素对象
  } else {
    elem = that.$refs[refname].$el.querySelector('input')// 获取页面input元素对象
  }

  // var elem = that.$refs[refname][0].$el.querySelector('input')// 获取页面input元素对象
  // 默认整数，小数位数为0
  if (typeof (decimalfixed) !== 'number') {
    decimalfixed = 0
  }
  // 获取输入框值
  var va = elem.value
  // 获取当前焦点位置
  var startPos = elem.selectionEnd
  if (va !== '') {
    // 获取焦点左侧字符
    var leftkeys = va.substring(0, startPos)
    // 获取焦点右侧字符
    var rightkeys = va.substring(startPos)
    // 分割小数点
    var spotArr = va.split('.')
    // 如果输入为整数或者要求格式为整数
    if (spotArr.length === 1 || decimalfixed === 0) {
      // 如果数字不为0，去除首字母的0
      if (leftkeys !== '0') {
        leftkeys = leftkeys.replace(/^[0]/, '')
      }
      leftkeys = leftkeys.replace(/[^0-9]/g, '')// 去除非数字的字符
      startPos = leftkeys.length// 获取格式化后的焦点位置
      rightkeys = rightkeys.replace(/[^0-9]/g, '')
      va = leftkeys + rightkeys
    } else {
      // 要求保留小数
      var spotLeft = spotArr[0]
      var spotRight = va.substring(spotLeft.length + 1)
      // 焦点左部分有小数点
      if (leftkeys.indexOf('.') > -1) {
        // 获取焦点左部分小数点右部分的字符
        var leftkeyspotRight = leftkeys.substring(spotLeft.length + 1)
        // 去除小数点左侧非数字字符
        spotLeft = spotLeft.replace(/[^0-9]/g, '')
        // 小数点左侧为空，补上0
        if (spotLeft === '') {
          spotLeft = '0'
        } else if (spotLeft !== '0') {
          // 小数点左侧不为0需要去除首字符的0
          spotLeft = spotLeft.replace(/^[0]/, '')
        }

        leftkeyspotRight = leftkeyspotRight.replace(/[^0-9]/g, '')
        // 格式化焦点左部分小数点右部分的字符，和小数点左侧字符拼接，目的是获得新焦点位置
        leftkeys = spotLeft + '.' + leftkeyspotRight
        // 获取拼接后左侧焦点新位置
        startPos = leftkeys.length
        // 格式化小数点右侧非数字字符
        spotRight = spotRight.replace(/[^0-9]/g, '')
        spotRight = spotRight.substring(0, decimalfixed)

        // 小数点左右侧数字拼接
        va = spotLeft + '.' + spotRight
      } else {
        // 焦点右部分有小数点
        // 焦点左部分格式化并获取新焦点位置
        leftkeys = leftkeys.replace(/^[0]/, '')
        leftkeys = leftkeys.replace(/[^0-9]/g, '')
        startPos = leftkeys.length
        // 格式化小数点左侧字符
        spotLeft = spotLeft.replace(/[^0-9]/g, '')
        // 小数点左侧为空要补0焦点右移
        if (spotLeft === '') {
          spotLeft = '0'
          if (startPos === 0) {
            startPos = 1
          }
        } else if (spotLeft !== '0') {
          // 去除首字符的0
          spotLeft = spotLeft.replace(/^[0]/, '')
        }
        spotRight = spotRight.replace(/[^0-9]/g, '')
        va = spotLeft + '.' + spotRight
      }
    }
  } else {
    va = va.replace(/\s+/g, '')
  }
  elem.value = va
  elem.setSelectionRange(startPos, startPos)// 设置输入焦点的位置
  return va
}
